package com.sys.web.controller;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.sys.constant.UserStatus;
import com.sys.dao.UserDao;
import com.sys.dao.impl.UserDaoImpl;
import com.sys.domain.User;
import com.sys.service.UserService;
import com.sys.service.impl.UserServiceImpl;
import com.sys.web.formbean.RegisterForm;

/**
 * @ClassName: UserServlet 
 * @Description: TODO(封装用户注册、登陆、退出、注销、修改密码的Servlet) 
 * @author 詹金浩 
 * @date 2018年3月10日 上午11:30:56
 */
@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//通过get方式在url后携带用户模块的操作信息
		String operation = request.getParameter("operation");
		if(operation.equals("register"))
			try {
				register(request, response);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		else if(operation.equals("login"))
			try {
				login(request, response);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		else if (operation.equals("quit")) {
			quit(request, response);
		}else if (operation.equals("changePwd")) {
			try {
				changPwd(request, response);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}else if (operation.equals("myHomeUI")) {
			response.sendRedirect(request.getContextPath()+"\\myHomeUI");
		}
	}
	
	/**
	 * @Title: changPwd
	 * @Description: TODO(修改密码) 
	 * @param request response
	 * @return void  修改成功回显true，失败回显信息错误。
	 * @throws SQLException ServletException IOException
	 */
	private void changPwd(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException, ServletException {
		HttpSession session = request.getSession();
		String userId = (String) session.getAttribute("user");
		String eMail = request.getParameter("eMail");
		String userPwd = request.getParameter("userPwd");
		String newPwd = request.getParameter("newPwd");
		UserService uService = new UserServiceImpl();
		Boolean b = uService.changeUserPwd(userId, eMail, userPwd, newPwd);
		if(b) {
			request.setAttribute("changeInfo", true);
			//如果设置了自动登陆，则修改Cookie
			Cookie []cookies = request.getCookies();
			if(cookies != null) {
				for(Cookie eCookie:cookies) {
					if(eCookie.getName()=="cookiePassword") {
						eCookie.setValue(newPwd);
						eCookie.setMaxAge(60*60*24*31);
						eCookie.setPath("/");
						response.addCookie(eCookie);
						break;
					}
				}
			}
			session.invalidate();
			request.getRequestDispatcher("/changePwdUI").forward(request, response);
		}else {
			request.setAttribute("changeInfo", false);
			request.getRequestDispatcher("/changePwdUI").forward(request, response);
		}
	}

	/**
	 * @Title: quit 
	 * @Description: TODO(析构session域实现用户退出) 
	 * @param request response
	 * @throws IOException
	 */
	private void quit(HttpServletRequest request, HttpServletResponse response) throws IOException {
		request.getSession().invalidate();
		request.getSession().setAttribute("quit", true);
		//如果是保存了自动登录，则自动登录失效
		Cookie []cookies = request.getCookies();
		if(cookies!=null) {
			for(Cookie eCookie: cookies) {
				if(eCookie.getName().equals("cookieUsername")||
						eCookie.getName().equals("cookiePassword")) {
					eCookie.setMaxAge(0);
					response.addCookie(eCookie);
				}
			}
		}
		//退出后返回主页
		response.sendRedirect(request.getContextPath() + "/homeUI");
		
	}

	/**
	 * @Title: register
	 * @Description: TODO(用户注册的Servlet) 
	 * @param request response
	 * @throws SQLException IOException ServletException
	 */
	private void register(HttpServletRequest request, HttpServletResponse response) throws SQLException, ServletException, IOException {
		User user = new RegisterForm().creatFormBean(request);
		user.setStatus(UserStatus.ACTIVE);
		UserDao userDao = new UserDaoImpl();
		userDao.add(user);
		request.getSession().setAttribute("user", user.getUserId());
		response.sendRedirect(request.getContextPath()+File.separator+"homeUI");
	}
	
	/**
	 * @Title: login 
	 * @Description: TODO(用户登录并且对勾选自动登录的用户设置Cookie发送到客户端实现自动登录) 
	 * @param request response
	 * @throws SQLException IOException
	 * @throws ServletException 
	 */ 
	private void login(HttpServletRequest request, HttpServletResponse response)
			throws SQLException, IOException, ServletException {
		UserService userService = new UserServiceImpl();
		String str = request.getParameter("userId");
		String pwd = request.getParameter("userPwd");
		if(str.equals("admin")&&pwd.equals("admin")){
			request.getSession().setAttribute("user", "admin");
			response.sendRedirect(request.getContextPath()+File.separator+"adminUI");
			return;
		}
		//检验用户名且密码是否正确
		Boolean isExist = userService.checkUserIsExist(str, pwd);
		String status = new UserDaoImpl().getStatus(str);
		HttpSession session = request.getSession();
		if(isExist&&status.equals("1")) {
			String msg = "";
			if(str.split("@").length == 2)
				msg = userService.getUserIdByEmail(str);
			else
				msg = str;
			//自动登录
			String autoLogin = request.getParameter("savePwd");
			if(autoLogin != null) {
				System.out.println(msg +" : 设置了自动登录！");
				//创建Cookie
				Cookie cookieUsername = new Cookie("cookieUsername",msg);
				Cookie cookiePassword = new Cookie("cookiePassword",pwd);
				//持久化时间为31天
				cookiePassword.setMaxAge(60*60*24*31);
				cookieUsername.setMaxAge(60*60*24*31);
				//设置cookie的携带路径，访问WEB应用所有的资源都携带此Cookie
				cookieUsername.setPath(request.getContextPath());
				cookiePassword.setPath(request.getContextPath());
				//向客户端发送Cookie	
				response.addCookie(cookieUsername);
				response.addCookie(cookiePassword);
			}
			//把用户存储在session域中
			session.setAttribute("user", msg);
			response.sendRedirect(request.getContextPath()+"/homeUI");
		}else if(!isExist){
			//回显登录失败的信息
			request.setAttribute("loginError", "用户名或密码错误！");
			request.getRequestDispatcher("/loginUI").forward(request, response);
		}else if (!status.equals("1")) {
			request.setAttribute("loginError", "此用户不可登录！");
			request.getRequestDispatcher("/loginUI").forward(request, response);
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
